package com.guofeng.rich.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guofeng.rich.gateway.constant.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

/**
 * @Author: guofeng
 * @Date: 2021/08/19/21:21
 * @Description:
 */
@Configuration
@Slf4j
public class TokenCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 自己的过滤器
     * 过滤器是 责任链模式
     * 过滤器能: token校验,ip限流,ip黑名单
     * webFlux Mono Flux 流式编程,响应式编程
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.request 先拿请求
        ServerHttpRequest request = exchange.getRequest();
        //获取请求地址
        String path = request.getPath().value();
        //判断是否是登陆地址
        if(GatewayConstant.ALLOW_URL.contains(path)){
            return chain.filter(exchange);
        }
        //判断token是否相同
        List<String> tokenLists = request.getHeaders().get(GatewayConstant.AUTH_TOKEN);
        if(!CollectionUtils.isEmpty(tokenLists)){
            String accessToken = tokenLists.get(0);
            if(!StringUtils.isEmpty(accessToken)){
              //和redis匹配一下 在获取Authorization的时候   是bearer编码格式的 空格区分
                Boolean flag = redisTemplate.hasKey(GatewayConstant.TOKEN_PREFIX + accessToken.split(" ")[1]);
                if(flag){
                    return chain.filter(exchange);
                }
            }
        }

        //代码运行到这,说明没有token 返回401的json串
        //1.拿到response
        ServerHttpResponse response = exchange.getResponse();
        //设置http的状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //响应JSON串,业务状态码,设置字符集
        response.getHeaders().add("content-type","application/json;charset=utf-8");
        //设置我们的业务状态码 数组桶大小 会找到最近的大一位的次方 扩容因子 0.75
        HashMap<String, Object> map = new HashMap<>(4);
        map.put("code",401);
        map.put("msg","未授权");
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = null;
        try {
           bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 该过滤器的执行顺序
     * 越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

}


































